package cn.com.common.job.task;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import cn.com.common.constants.Constants;
import cn.com.gas.entity.GasAnalyseRatioRingEntity;
import cn.com.gas.entity.GasAnalyseRatioWithEntity;
import cn.com.gas.entity.GasStationDeptEntity;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.entity.GasStaytimeResultEntity;
import cn.com.gas.service.GasAnalyseRatioRingService;
import cn.com.gas.service.GasAnalyseRatioWithService;
import cn.com.gas.service.GasStationDeptService;
import cn.com.gas.service.GasStationinfoService;
import cn.com.gas.service.GasStaytimeResultService;
import cn.com.util.TsBqUtils;

/**
 * 月销环比分析 月销同比分析 testTask为spring bean的名称， 方法名称必须是run
 *
 * @author wenbin
 * @version V1.0
 * @date 2024年4月18日
 */
@Component("gasAnalyseMonthRatioProcessTask")
@DisallowConcurrentExecution
public class GasAnalyseMonthRatioProcessTask {

	@Value("${gasstation.timedTask.gasAnalyseMonthRatioProcessTask}")
	private String gasAnalyseMonthRatioProcessTask;

	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private GasStationinfoService gasStationinfoService;
	@Autowired
	private GasStaytimeResultService gasStaytimeResultService;
	@Autowired
	private GasAnalyseRatioRingService gasAnalyseRatioRingService;
	@Autowired
	private GasAnalyseRatioWithService gasAnalyseRatioWithService;
	@Autowired
	private GasStationDeptService gasStationDeptService;

	LocalDate now = LocalDate.now();
	LocalDate firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());
	LocalDate firstDayOfNextMonth = now.with(TemporalAdjusters.firstDayOfNextMonth());
	int year = now.getYear(); // 获取当前年份
	int month = now.getMonthValue(); // 获取当前月份
	String monthYear = handleMonthYear(month, year);
	String monthYearBefore = beforeMonthYear(month, year);

	public void run(String params) {
		logger.debug("gasAnalyseMonthRatioProcessTask定时任务正在执行，参数为：{}", params);

		logger.debug("application参数为gasAnalyseMonthRatioProcessTask：{}", gasAnalyseMonthRatioProcessTask);

		if (gasAnalyseMonthRatioProcessTask.equals(Constants.JOB_START)) {

			if (TsBqUtils.isNotNull(params)) {
				String year = params.substring(0, 4);
				String month = params.substring(4, 6);

				DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
				LocalDate localDate = LocalDate.parse(params + "01", formatter);
				firstDayOfMonth = localDate.with(TemporalAdjusters.firstDayOfMonth());
				firstDayOfNextMonth = localDate.with(TemporalAdjusters.firstDayOfNextMonth());

				monthYear = params;
				monthYearBefore = Integer.parseInt(year) - 1 + month;
			}

			logger.debug("加工 当前 月时间：{}", firstDayOfMonth, firstDayOfNextMonth);
			logger.debug("加工 当前 年月时间：{}", monthYear);
			logger.debug("加工 上一 年月时间：{}", monthYearBefore);
			List<String> pid = new ArrayList<>();

			List<GasStationDeptEntity> listGasStationDept = gasStationDeptService.list(Wrappers.lambdaQuery());
			if (TsBqUtils.isNotNull(listGasStationDept)) {
				for (GasStationDeptEntity gasStationDeptEntity : listGasStationDept) {
					pid.add(gasStationDeptEntity.getEndangerId());
				}

				LambdaQueryWrapper<GasStationinfoEntity> queryWrapper = Wrappers.lambdaQuery();

				queryWrapper.in(GasStationinfoEntity::getPid, pid);
				queryWrapper.eq(GasStationinfoEntity::getType, "group");
				queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");

				List<GasStationinfoEntity> gasStationinfoList = gasStationinfoService.list(queryWrapper);

				for (GasStationinfoEntity gasStationinfoEntity : gasStationinfoList) {
					// 处理加油站 名称
					if (gasStationinfoEntity.getType().equals("group")
							|| gasStationinfoEntity.getType().equals("domain")) {
						gasStationinfoEntity
								.setName(TsBqUtils.handleEndBeforeParentheses(gasStationinfoEntity.getName()));
					}

					// 计算累计金额
					BigDecimal result = new BigDecimal(0);
					String id = gasStationinfoEntity.getId();

					LambdaQueryWrapper<GasStaytimeResultEntity> queryWrapper1 = Wrappers.lambdaQuery();
					queryWrapper1.eq(GasStaytimeResultEntity::getStationId, id);
					// 当前月
			        Date firstDayOfMonthDate = Date.from(firstDayOfMonth.atStartOfDay(ZoneId.systemDefault()).toInstant());
			        Date firstDayOfNextMonthDate = Date.from(firstDayOfNextMonth.atStartOfDay(ZoneId.systemDefault()).toInstant());
					queryWrapper1.ge(GasStaytimeResultEntity::getMessageDisappear, firstDayOfMonthDate);
					queryWrapper1.lt(GasStaytimeResultEntity::getMessageDisappear, firstDayOfNextMonthDate);

					List<GasStaytimeResultEntity> list = gasStaytimeResultService.list(queryWrapper1);
					for (GasStaytimeResultEntity gasStaytimeResultEntity : list) {
						String price = gasStaytimeResultEntity.getPrice();
						BigDecimal _price = new BigDecimal(price);
						result = result.add(_price);
					}

					gasStationinfoEntity.setPrice(result.toString());
					gasStationinfoEntity.setSaleAmount(list.size() + "");

					// 环比分析 Ring
					analyseRatioRing(gasStationinfoEntity);
					// 同比分析 With
					analyseRatioWith(gasStationinfoEntity);

				}

			} else {
				logger.error("GasStationDept表为配置数据");
			}

		} else {
			logger.debug("application配置文件控制不执行gasAnalyseMonthRatioProcessTask定时任务");

		}

	}

	// 环比分析
	private void analyseRatioRing(GasStationinfoEntity station) {
		station.setYearMonths(monthYear);

		gasAnalyseRatioRingService.realRemoveById(station);

		LambdaQueryWrapper<GasAnalyseRatioRingEntity> queryWrapper1 = Wrappers.lambdaQuery();
		queryWrapper1.eq(GasAnalyseRatioRingEntity::getYearMonths, monthYearBefore);
		queryWrapper1.eq(GasAnalyseRatioRingEntity::getStationId, station.getId());
		List<GasAnalyseRatioRingEntity> ratioRingList1 = gasAnalyseRatioRingService.list(queryWrapper1);

		String upSale = "0";
		String upSaleAmount = "0";
		if (TsBqUtils.isNotNull(ratioRingList1)) {
			upSale = ratioRingList1.get(0).getSale();
			if(TsBqUtils.isNotNull(ratioRingList1.get(0).getUpSaleAmount())){
				upSaleAmount = ratioRingList1.get(0).getUpSaleAmount();
			}

		}

		GasAnalyseRatioRingEntity gasAnalyseRatioRingEntity = new GasAnalyseRatioRingEntity();
		String sale = "0";
		if (TsBqUtils.isNotNull(station.getPrice())) {
			sale = station.getPrice();
		}

		String saleAmount = "0";
		if (TsBqUtils.isNotNull(station.getSaleAmount())) {
			saleAmount = station.getSaleAmount();
		}

		logger.info("加油站ID:upSale:upSaleAmount:sale:saleAmount" + station.getId()+ ":" + upSale + ":" + upSaleAmount + ":"
				+ sale + ":" + saleAmount);

		gasAnalyseRatioRingEntity.setStationName(station.getName());
		gasAnalyseRatioRingEntity.setSale(sale);

		gasAnalyseRatioRingEntity.setUpSale(upSale);
		// 环比增长率计算公式为环比增长率=（本期数－上期数）/上期数×100%
		gasAnalyseRatioRingEntity.setRatioRing(getRatioRing(upSale, sale));
		gasAnalyseRatioRingEntity.setYearMonths(monthYear);
		gasAnalyseRatioRingEntity.setTaxorgcode(station.getTaxorgcode());
		gasAnalyseRatioRingEntity.setStationId(station.getId());

		gasAnalyseRatioRingEntity.setSaleAmount(saleAmount);
		gasAnalyseRatioRingEntity.setUpSaleAmount(upSaleAmount);
		gasAnalyseRatioRingEntity.setRatioRingAmount(getRatioRing(upSaleAmount, saleAmount));

		gasAnalyseRatioRingEntity.setDeleted(Constants.DATA_NOT_DELETED);
		gasAnalyseRatioRingEntity.setCreateId("sys_job");
		gasAnalyseRatioRingEntity.setCreateTime(Date.from(now.atStartOfDay(ZoneId.systemDefault()).toInstant()));
		gasAnalyseRatioRingService.save(gasAnalyseRatioRingEntity);

	}

	// 同比分析
	private void analyseRatioWith(GasStationinfoEntity station) {
		station.setYearMonths(monthYear);

		gasAnalyseRatioWithService.realRemoveById(station);

		/**/

		LambdaQueryWrapper<GasAnalyseRatioWithEntity> queryWrapper1 = Wrappers.lambdaQuery();

		queryWrapper1.eq(GasAnalyseRatioWithEntity::getYearMonths, handleMonthYear(month, year - 1));
		queryWrapper1.eq(GasAnalyseRatioWithEntity::getStationId, station.getId());

		List<GasAnalyseRatioWithEntity> ratioWithList1 = gasAnalyseRatioWithService.list(queryWrapper1);

		String upSale = "0";
		String upSaleAmount = "0";
		if (TsBqUtils.isNotNull(ratioWithList1)) {
			upSale = ratioWithList1.get(0).getSale();
			upSaleAmount = ratioWithList1.get(0).getUpSaleAmount();

		}

		GasAnalyseRatioWithEntity gasAnalyseRatioWithEntity = new GasAnalyseRatioWithEntity();
		String sale = station.getPrice();

		String saleAmount = "0";
		if (TsBqUtils.isNotNull(station.getSaleAmount())) {
			saleAmount = station.getSaleAmount();
		}

		gasAnalyseRatioWithEntity.setStationName(station.getName());
		gasAnalyseRatioWithEntity.setSale(sale);
		gasAnalyseRatioWithEntity.setUpSale(upSale);
		// 同比增长率计算公式为同比增长率=（本期数－同期数）/同期数×100%
		gasAnalyseRatioWithEntity.setRatioWith(getRatioWith(upSale, sale));
		gasAnalyseRatioWithEntity.setYearMonths(monthYear);
		gasAnalyseRatioWithEntity.setTaxorgcode(station.getTaxorgcode());
		gasAnalyseRatioWithEntity.setStationId(station.getId());

		gasAnalyseRatioWithEntity.setSaleAmount(saleAmount);
		gasAnalyseRatioWithEntity.setUpSaleAmount(upSaleAmount);
		gasAnalyseRatioWithEntity.setRatioWithAmount(getRatioWith(upSaleAmount, saleAmount));

		gasAnalyseRatioWithEntity.setDeleted(Constants.DATA_NOT_DELETED);
		gasAnalyseRatioWithEntity.setCreateId("sys_job");
		gasAnalyseRatioWithEntity.setCreateTime(Date.from(now.atStartOfDay(ZoneId.systemDefault()).toInstant()));
		gasAnalyseRatioWithService.save(gasAnalyseRatioWithEntity);
	}

	private static String handleMonthYear(int month, int year) {
		if (month <= 9) {
			return year + "0" + month;
		} else {
			return year + "" + month;
		}
	}

	private static String beforeMonthYear(int month, int year) {
		if (month == 1) {
			return year - 1 + "12";
		} else {
			int _month = month - 1;
			return handleMonthYear(_month, year);
		}
	}

	private static String getRatioRing(String upSale, String sale) {
		if (upSale.equals("0") || sale.equals("0")) {
			return "0";
		}

		// 环比增长率计算公式为环比增长率=（本期数－上期数）/上期数×100%
		BigDecimal _upSale = new BigDecimal(upSale);
		BigDecimal _sale = new BigDecimal(sale);
		BigDecimal result = (_sale.subtract(_upSale)).divide(_upSale, 2, BigDecimal.ROUND_HALF_UP);

		return result.multiply(new BigDecimal(100)).toString() + "%";
	}

	private static String getRatioWith(String upSale, String sale) {
		if (upSale.equals("0") || sale.equals("0")) {
			return "0";
		}

		// 同比增长率计算公式为同比增长率=（本期数－同期数）/同期数×100%
		BigDecimal _upSale = new BigDecimal(upSale);
		BigDecimal _sale = new BigDecimal(sale);
		BigDecimal result = (_sale.subtract(_upSale)).divide(_upSale, 2, BigDecimal.ROUND_HALF_UP);
		return result.multiply(new BigDecimal(100)).toString() + "%";
	}

	public static void main(String[] args) {

	}

}
